using System;

namespace Jerry.UiFrame
{
    public class Timer
    {
        private readonly bool _bLoop; //是否循环调用
        private readonly float _duration; //持续时间
        private readonly Action _onComplete; //计时器完成回调
        private float _remainingTime; //剩余时间

        internal int Id;

        public Timer(float duration, Action onComplete, bool bLoop = false, bool bUseUnscaledTime = false)
        {
            _duration = duration;
            _remainingTime = duration;
            _onComplete = onComplete;
            _bLoop = bLoop;
            BUseUnscaledTime = bUseUnscaledTime;
        }

        public bool BUseUnscaledTime { get; } //是否忽略Time.Scale的影响

        /// <summary>
        ///     定时器的状态
        ///     <para></para>
        /// </summary>
        internal bool IsPaused { get; private set; }

        /// <summary>
        ///     定时器是否结束
        /// </summary>
        internal bool IsDone { get; private set; }

        /// <summary>
        ///     定时器进度
        /// </summary>
        public float Progress => 1 - _remainingTime / _duration;

        internal void Update(float deltaTime)
        {
            if (IsPaused || IsDone)
                return;
            _remainingTime -= deltaTime;

            if (_remainingTime <= 0) //定时的时间到了
            {
                _onComplete?.Invoke();
                if (_bLoop)
                    _remainingTime = _duration;
                else
                    IsDone = true;
            }
        }

        /// <summary>
        ///     暂定计时器
        /// </summary>
        internal void Pause()
        {
            IsPaused = true;
        }

        /// <summary>
        ///     恢复计时器
        /// </summary>
        internal void Resume()
        {
            IsPaused = false;
        }

        /// <summary>
        ///     停止定时器
        /// </summary>
        internal void Stop()
        {
            IsDone = true;
        }

        /// <summary>
        ///     重新开始定时器
        /// </summary>
        internal void Restart()
        {
            _remainingTime = _duration;
        }
    }
}